﻿using System;
using System.Linq;
using System.Web.Mvc;
using Framework.Poco;
using System.Collections.Generic;
using Shell.DomainDot;
using Framework.Domain;

namespace Framework.Mvc
{
    public class UserModelBinder : DefaultModelBinder, IModelBinder
    {
        static UserModelBinder()
        {
            UserModelBinderModelName = "currentUser";
        }

        public static string UserModelBinderModelName;

        public IEnumerable<User> StoredUsers()
        {
            IDomainDotFactory factory = DomainDotFactory.Factory;
            var context = factory.Create<UserRegisterContext>();
            return context.GetAllUsers();
        }

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelName.Equals(UserModelBinderModelName, StringComparison.CurrentCulture))
            {
                var identity = controllerContext.HttpContext.User.Identity;
                if (identity.IsAuthenticated)
                {
                    return this.StoredUsers().SingleOrDefault(u => u.Name.Equals(identity.Name, StringComparison.CurrentCultureIgnoreCase));
                }
                else
                {
                    return null;
                }
            }
            return base.BindModel(controllerContext, bindingContext);
        }
    }
}
